<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="896" @ok="handleSubmit">
      <BasicForm @register="registerForm" ref="formref">
        <template #cardNumberSlot="{ model, field }">
          <a-input v-model:value="model[field]" type="Input" @blur="addZero" :disabled="isUpdate" required placeholder="请输入卡号!" length="20"/>
          <a-button v-if="!isUpdate" @click="readCard">读卡</a-button><!--&nbsp;&nbsp;&nbsp;
          <a-button @click="addZero">补零</a-button>-->
        </template>
      </BasicForm>
    <template #insertFooter>
      <!-- <a-button :type="okType"  :loading="confirmLoading" @click="handleNormal" v-if="isUpdate" >
        激活
      </a-button> -->
      <a-button :type="okType"  :loading="confirmLoading"  @click="reportLostFrom" v-if="isUpdate" >
        挂失
      </a-button>
      <a-button :type="okType"  :loading="confirmLoading" @click="releaseLostFrom" v-if="isUpdate" >
        解挂
      </a-button>
      <a-button :type="okType"  :loading="confirmLoading" @click="backcardForm" v-if="isUpdate" >
        退卡
      </a-button>
      <a-button :type="okType"  :loading="confirmLoading" @click="handlerrecard" v-if="isUpdate" >
        补卡
      </a-button>
<!--      <a-button :type="okType"  :loading="confirmLoading" @click="handlercollect" v-if="isUpdate" >
        回收
      </a-button>-->

    </template>
    <template #insertSpace>
      <div style="display:inline-block;width:430px"></div>
    </template>
    <SsCardModalRecard @register="registerModalRecard" @success="handleSuccess"></SsCardModalRecard>
  </BasicModal>

</template>

<script lang="ts" setup>
    import { cloneDeep } from 'lodash-es';
    import {ref, computed, unref, nextTick,createVNode} from 'vue';
    import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
    import { Modal } from 'ant-design-vue';
    import SsCardModalRecard from '/@/views/baseinfo/card/components/SsCardModalRecard.vue'
    import {BasicModal, useModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, FormSchema, useForm} from '/@/components/Form/index';
    import {formSchema, formSchemaByPerson} from '/@/views/baseinfo/card/SsCard.data';
    import {saveOrUpdate,normal,releaseLost,reportLost,backcard,recollect,recard,list as listcard} from '/@/views/baseinfo/card/SsCard.api';
    import {list} from "@/views/baseinfo/person/SsPerson.api";
    import {defHttp} from "@/utils/http/axios";
    import {useMessage} from "@/hooks/web/useMessage";
    import {onMountedOrActivated} from "@/hooks/core/onMountedOrActivated";
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const formref = ref({});
    const { createMessage } = useMessage();
    const [registerModalRecard, {openModal:openModalRecard}] = useModal();



    onMountedOrActivated(()=>{
    //  console.log(formSchema)
    //  console.log(formSchema[5])
     // formSchema[5].dynamicDisabled = true;
      //  updateSchema({field:"personId",dynamicDisabled:false})
    })


    //表单配置
    const [registerForm, {getForm,setProps,resetFields, setFieldsValue,getFieldsValue, validate,updateSchema}] = useForm({
        labelWidth: 150,
        schemas: formSchemaByPerson,
        showActionButtonGroup: false,
        baseColProps: {span: 12},
      wrapperCol: {
        xxl: 12,
      },
     // layout: 'inline',
      //默认row行配置,当 layout 为 inline 生效
    //  rowProps: { gutter: 24, justify: 'center', align: 'middle' },
    });
    function formaData(timer) {
      const year = timer.getFullYear()
      const month = timer.getMonth() + 1 // 由于月份从0开始，因此需加1
      const day = timer.getDate()
      const hour = timer.getHours()
      const minute = timer.getMinutes()
      const second = timer.getSeconds()
      return `${pad(year, 4)}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`
    }
    function pad(timeEl, total = 2, str = '0') {
      return timeEl.toString().padStart(total, str)
    }
    function addZero(){
      let cn = getFieldsValue().cardNumber;
      let cn1 = addZeroExt(cn);
      setFieldsValue({cardNumber:cn1});
    }
    function addZeroExt(cn){
      let len = cn.length;
      for(let i = 0;i<10-len;i++){
        cn = "0"+cn;
      }
      return  cn ;
    }
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await resetFields();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
         // let temp = unref(formref).formModel.personId;
       //   console.log(temp)

          let recordPerson = data.recordPerson;
          changeEvent(recordPerson);
        }else{
          let recordPerson = data.recordPerson;
          changeEvent(recordPerson);

          let now = new Date();
          await  setFieldsValue({startDate:formaData(new Date())})
          now.setFullYear(now.getFullYear()+3);
          console.log(now)
          await  setFieldsValue({endDate:formaData(now)})
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

    function changeEvent(recordPerson){
      if(recordPerson){
        nextTick(()=>{
          unref(formref).formModel.personName = recordPerson.name;
          unref(formref).formModel.personCode = recordPerson.code;
          unref(formref).formModel.personDept = recordPerson.departmentId_dictText;
          unref(formref).formModel.personType = recordPerson.personType;
          unref(formref).formModel.personId = recordPerson.id;
        })

        return;
      }
/*      let params = {id:recordPerson.id};
      console.log(params);
      let res =  list(params);
      res.then((data)=>{
        console.log(data);
        if(data.records?.length>0){
          unref(formref).formModel.personName = recordPerson.name;
          unref(formref).formModel.personCode = recordPerson.code;
          unref(formref).formModel.personDept = recordPerson.departmentId_dictText;
          unref(formref).formModel.personType = recordPerson.personType;
          unref(formref).formModel.personId = recordPerson.id;
        }

      })*/
    }
    //表单提交事件
    async function handleSubmit(v) {
        try {
            let values = await validate();
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(values, isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }


   async function handleSuccess(){
      let values = await validate();
      let res = await listcard({id:values.id});
      console.log(values)
     await setFieldsValue({
       ...res.records[0],
     });
    }

    async function handlercollect(){
      let values = await validate();
      await recollect({ids: values.id}, handleSuccess);
    }
  //挂失
   function reportLostFrom(){
    Modal.confirm({
        title: '挂失',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确认要做挂失操作吗？',
        okText: '确认',
        cancelText: '取消',
        onOk:handlereportLost
      });
    }
    async function handlereportLost(){
      let values = await validate();
      await reportLost({ids: values.id}, handleSuccess);
    }
    async function handleNormal(){
      let values = await validate();
      await normal({ids:  values.id}, handleSuccess);
    }
    //解除
    function releaseLostFrom(){
    Modal.confirm({
        title: '解挂',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确认要做解挂操作吗？',
        okText: '确认',
        cancelText: '取消',
        onOk:handlereleaseLost
      });
    }
    async function handlereleaseLost(){
      let values = await validate();
      await releaseLost({ids:  values.id}, handleSuccess);
    }
    //退卡
    function backcardForm(){
      Modal.confirm({
        title: '退卡',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确认要做退卡操作吗？',
        okText: '确认',
        cancelText: '取消',
        onOk:handlerbackcard
      });
    }

    async function handlerbackcard(){
      let values = await validate();
      await backcard({ids:  values.id}, handleSuccess);
    }
    async function handlerrecard() {
      let values = await validate();
      const record = values;
      openModalRecard(true, {
        closePm,
        record,
        isUpdate: true,
        showFooter: true,
      });
    }
    function closePm(){
      closeModal();
    }


    //根据卡号查询会员信息
    function readCard() {
/*      let tt = "SUCC-739729888";
      var t1 = tt.substring(0, 5);
      var t2 = tt.substring(5);
      console.log(t1);
      console.log(t2);
      if(1==1){
        if ("EROR-" == t1) {
          createMessage.error('提示:'+t1);
          return false;
        } else if ("SUCC-" == t1) {
          console.log("卡号=" + t2);
          setFieldsValue({cardNumber:t2});
          return true;
        } else {
          createMessage.warn('提示:'+this.responseText);
          return false;
        }
        return;
      }*/


      // （1） 获取 XMLHttpRequest对象
      let xmlHttp = new XMLHttpRequest();

      //  (2) 连接服务器
      //  get
      //xmlHttp.open("get","/sendAjax/?a=1&b=2");

      //  post
      xmlHttp.open("post","http://127.0.0.1:19999/dllinterface");

      // 设置请求头的Content-Type
      xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

      // （3） 发送数据
      // （4） 回调函数  success
      xmlHttp.onreadystatechange = function() {
        console.log(this);
        console.log(this.readyState);
        console.log(this.status);
        if(this.readyState==4 && this.status==200){
          console.log(this.responseText)
          var respHead = this.responseText.substring(0, 5);
          var respMsg = this.responseText.substring(5);
          console.log(respHead);
          console.log(respMsg);
          if ("EROR-" == respHead) {
            createMessage.error('提示:'+respMsg);
            return false;
          } else if ("SUCC-" == respHead) {
            console.log("卡号=" + respMsg);
            let cn1 = addZeroExt(respMsg);
            setFieldsValue({cardNumber:cn1});
            return true;
          } else {
            createMessage.warn('提示:'+this.responseText);
            return false;
          }
        }
      };

      xmlHttp.send('JBDL') ;   // 请求体数据

    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>
